const _cmsMongo = global._cmsMongo

module.exports = {
	getModuleTree: async function() {
		let moduleCol = await _cmsMongo.getCollection('module')
		let moduleList = await moduleCol.find({}, {
			create_time: 0,
			modify_time: 0,
		}).sort({
			create_time: 1,
		}).toArray()
		let moduleMap = {}
		let treeData = []
		for (let i = 0; i < moduleList.length; i++) {
			let module = moduleList[i]
			if (module.parent_id == 0)
				treeData.push(module)
			else
				moduleMap[module.module_id] = module
		}
		treeData.forEach(module => addChildren(module, moduleMap))
		return treeData
	}
}

function addChildren(module, moduleMap) {
	if (!module || !Array.isArray(module.children))
		return
	let children = module.children
	module.children = []
	for (let i = 0; i < children.length; i++) {
		let cmId = children[i]
		let m = moduleMap[cmId]
		if (m) {
			module.children.push(m)
			if (Array.isArray(m.children))
				addChildren(m, moduleMap)
		}
	}
}